package com.topvision.prlibrary;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Rect;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.kernal.plateid.PlateCfgParameter;
import com.kernal.plateid.PlateRecognitionParameter;

public class PlatManager {

    public static final String TAG = "tv-plat";
    private final int PLAT_SCORE = 75;
    private static PlatManager ourInstance;
    private RecogService.MyBinder recogBinder;
    private int iInitPlateIDSDK = -1;
    private final int imageFormat = 6;// NV21 -->6
    private Context mContext;
    private PlateRecognitionParameter prp;
    //0结果，1颜色，2颜色类型，3车牌类型，4置信度、5亮度、6方向、7左，8上，9右，10下（7.8.9.10是车牌区域范围）11时间，12车身亮度，13车身颜色
    private String[] fieldvalue = new String[14];
    private int nRet = -2;
    private PlatCallback platCallback;
    private int currentYear;
    private int left, right, bottom, top;

    public static PlatManager getInstance() {
        if (ourInstance == null) {
            synchronized (PlatManager.class) {
                if (ourInstance == null) {
                    ourInstance = new PlatManager();

                }
            }
        }

        return ourInstance;
    }

    private PlatManager() {
        //快速模式，true为精准模式
        RecogService.recogModel = false;
        //视频流模式
        RecogService.initializeType = true;
        prp = new PlateRecognitionParameter();
        // 开发码
        prp.devCode = Devcode.DEVCODE;
        prp.plateIDCfg.bRotate = 0;

    }


    /**
     * 初始化车牌引擎
     *
     * @param mContext 上下文
     */
    public void initPlatEngine(Context mContext) {
        if (mContext == null)
            return;
        this.mContext = mContext;
        Intent authIntent = new Intent(mContext,
                RecogService.class);
        mContext.bindService(authIntent, recogConn, Service.BIND_AUTO_CREATE);
    }

    public void destroyPlatEngine(Context mContext) {
        if (recogBinder != null) {
            mContext.unbindService(recogConn);
            recogBinder = null;
        }
        ourInstance = null;
    }

    public PlatResultEntity platOcr(byte[] nv21Data, int previewWidth, int previewHeight) {
        if (iInitPlateIDSDK == 0) {
            prp.height = previewHeight;
            prp.width = previewWidth;
            // Log.e(PlatConstants.TAG, "width=" + previewWidth + ",height=" + previewHeight);
            prp.plateIDCfg.left = 0;
            prp.plateIDCfg.right = previewWidth;
            prp.plateIDCfg.bottom = previewHeight;
            prp.plateIDCfg.top = 0;
//            setHorizontalRegion(previewWidth, previewHeight);
            prp.picByte = nv21Data;
            long startTime = System.currentTimeMillis();
            fieldvalue = recogBinder.doRecogDetail(prp);
            Log.i(TAG, String.valueOf(System.currentTimeMillis() - startTime));
            nRet = recogBinder.getnRet();
            return setRecogResult(fieldvalue);
        }
        return null;
    }

    public PlatResultEntity platOcr(String filePath) {
        if (iInitPlateIDSDK == 0) {
            int[] imageWidthHeight = ImageUtil.getImageWidthHeight(filePath);
            return platOcr(ImageUtil.convertNv21(filePath), imageWidthHeight[0], imageWidthHeight[1]);
        }
        return null;
    }

    private PlatResultEntity setRecogResult(String[] recogResult) {
        String result = recogResult[0];
        // Log.e("tvLog2", "result=" + result);
        //识别结果不为空
        if (!TextUtils.isEmpty(result)) {
            PlatResultEntity platResultEntity = new PlatResultEntity();
            platResultEntity.setNumber(recogResult[0]);
            platResultEntity.setColor(recogResult[1]);
            platResultEntity.setColorType(recogResult[2]);
            platResultEntity.setCardNumberType(recogResult[3]);
            String[] scoreArray = recogResult[4].split(";");
            platResultEntity.setScore(scoreArray[0]);
//                int left = Integer.parseInt(recogResult[7]);
//                int top = Integer.parseInt(recogResult[8]);
//                int right = Integer.parseInt(recogResult[9]);
//                int bottom = Integer.parseInt(recogResult[10]);
            int left = prp.plateIDCfg.left;
            int top = prp.plateIDCfg.top;
            int right = prp.plateIDCfg.right;
            int bottom = prp.plateIDCfg.bottom;
            //Log.e("tvLog", "left=" + left + ",top=" + top + ",right=" + right + ",bottom=" + bottom);
            Rect rect = new Rect(left, top, right, bottom);
            platResultEntity.setRect(rect);
            return platResultEntity;
        }
        return null;
    }

    //设置车牌识别区域
    public void setRecogPosition(int left, int right, int top, int bottom) {
        this.left = left;
        this.right = right;
        this.top = top;
        this.bottom = bottom;
    }

    /**
     * 设置横屏时的真实识别区域
     * configManager.cameraResolution.x：预览分辨率的宽
     * configManager.cameraResolution.y：预览分辨率的高
     */
    private void setHorizontalRegion(int previewWidth, int previewHeight) {
        prp.plateIDCfg.left = previewWidth / 4;
        prp.plateIDCfg.top = previewHeight / 4;
        prp.plateIDCfg.right = previewWidth / 4 + previewWidth / 2;
        prp.plateIDCfg.bottom = previewHeight - previewHeight / 4;
    }


    private ServiceConnection recogConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            recogConn = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            recogBinder = (RecogService.MyBinder) service;
            iInitPlateIDSDK = recogBinder.getInitPlateIDSDK();
            if (iInitPlateIDSDK != 0) {
                Toast.makeText(mContext, "错误码：" + iInitPlateIDSDK, Toast.LENGTH_LONG).show();
                if (platCallback != null)
                    platCallback.initPlatEngineCallback(false, "errorCode:" + iInitPlateIDSDK);
            } else {
                PlateCfgParameter cfgparameter = new PlateCfgParameter();
                cfgparameter.armpolice = 4;
                cfgparameter.armpolice2 = 16;
                cfgparameter.embassy = 12;
                cfgparameter.individual = 0;
                // cfgparameter.nContrast = 9;
                cfgparameter.nOCR_Th = 0;
                cfgparameter.nPlateLocate_Th = 5;
                cfgparameter.onlylocation = 15;
                cfgparameter.tworowyellow = 2;
                cfgparameter.tworowarmy = 6;
                cfgparameter.szProvince = "";
                cfgparameter.onlytworowyellow = 11;
                cfgparameter.tractor = 8;
                cfgparameter.bIsNight = 1;
                //新能源车牌开启
                cfgparameter.newEnergy = 24;
                //领事馆车牌开启;
                cfgparameter.consulate = 22;
                recogBinder.setRecogArgu(cfgparameter, imageFormat, 0,
                        1);
                if (platCallback != null)
                    platCallback.initPlatEngineCallback(true, "success");
            }
        }
    };

    public PlatCallback getPlatCallback() {
        return platCallback;
    }

    public void setPlatCallback(PlatCallback platCallback) {
        this.platCallback = platCallback;
    }
}
